const inquirer = require('inquirer');
const fs = require('fs');
const path = require('path');
const ExcelJS = require('exceljs');
const Utils = require('./utils/index.js');
const Table = require('./class/Table.js');
const Column = require('./class/Column.js');
const Row = require('./class/Row.js');
const table = new Table({ name: 'my table' });

let outputFilename = Utils.round() + '.xlsx';
const result = new Set();

if (process.argv.slice(2)[0]) {
  const f = process.argv.slice(2)[0];
  const isRightFile = Utils.checkInputFilePath(f);

  if (!isRightFile) {
    console.log('输入的文件路径错误，请重新输入，注意：仅支持txt, json两种类型的文件');
    stepCommand();
  }

  const targetFile = path.resolve(process.argv.slice(2)[0]);

  outputFilename = Utils.getFilenameAndExtByPath(f)[1] + '.' + Utils.round() + '.xlsx';
  execTrans(targetFile);
} else {
  stepCommand();
}

function stepCommand() {
  inquirer
    .prompt([{
      type: 'input',
      message: '请将要解析的json文件拖拽进来, 按回车键执行',
      name: 'filename',
      default: '',
    }])
    .then(({ filename }) => {
      if (!filename || !Utils.checkInputFilePath(filename.toString().trim())) {
        console.log('文件路径参数不正确, 请重新输入');
        stepCommand();
      } else {
        outputFilename = Utils.getFilenameAndExtByPath(filename.toString())[1] + '.' + Utils.round() + '.xlsx';
        execTrans(filename.toString().trim());
      }
    })
    .catch((e) => {
      console.log(e);
    });
}

// 执行解析（通用）
function execTrans(targetFile) {
  let JsonFile = JSON.parse(fs.readFileSync(targetFile, 'utf-8'));
  const workbook = new ExcelJS.Workbook();

  workbook.creator = 'Me';

  workbook.views = [
    {
      x: 0,
      y: 0,
      width: 10000,
      height: 20000,
      firstSheet: 0,
      activeTab: 1,
      visibility: 'visible',
    },
  ];

  const sheet = workbook.addWorksheet('My Sheet', {
    views: [{ xSplit: 1, ySplit: 1 }],
  });

  // 递归解析数据
  function complierOriginData(array) {
    if (array instanceof Array) {
      for (let index = 0; index < array.length; index++) {
        const item = array[index];

        for (const key in item) {
          if (item[key] instanceof Array) {
            const _arr = item[key].map((iv) => {
              const obj = {};

              for (const sk in iv) {
                obj[key + '.' + sk] = iv[sk];
              }

              return obj;
            });
            // delete item[key];
            complierOriginData(_arr);
          } else if (item[key] instanceof Object) {
            for (const sk in item[key]) {
              if (Array.isArray(item[key][sk])) {
                const _arr = item[key][sk].map((iv) => {
                  const obj = {};

                  for (const vk in iv) {
                    obj[key + '.' + sk + '.' + vk] = iv[vk];
                  }

                  return obj;
                });
                // delete item[key][sk];
                complierOriginData(_arr);
              } else if (item[key][sk] instanceof Object) {
                // obj[key + "." + sk] = item[key][sk];
                // 修改对象属性名称，返回新的对象
                const prefix = `${key}.${sk}`;
                const obj = Utils.transformObjectKeys(item[key][sk], prefix);
                // delete item[key][sk];
                complierOriginData(obj);
              } else {
                result.add(item[key]);
              }
            }
          } else {
            result.add(item);
          }
        }
      }
    }
    // 解析的数据是对象
    else if (array instanceof Object) {
      for (const key in array) {
        if (array[key] instanceof Array) {
          const _arr = array[key].map((iv) => {
            const obj = {};

            for (const sk in iv) {
              obj[key + '.' + sk] = iv[sk];
            }

            return obj;
          });
          // delete array[key];
          complierOriginData(_arr);
        } else if (array[key] instanceof Object) {
          for (const sk in array[key]) {
            if (array[key][sk] instanceof Array) {
              const _arr = array[key][sk].map((iv) => {
                const obj = {};

                for (const vk in iv) {
                  obj[key + '.' + sk + '.' + vk] = iv[vk];
                }

                return obj;
              });
              // delete array[key][sk];
              complierOriginData(_arr);
            } else if (array[key][sk] instanceof Object) {
              const prefix = `${key}.${sk}`;
              const obj = Utils.transformObjectKeys(array[key][sk], prefix);
              // delete array[key][sk];
              complierOriginData(obj);
            } else {
              result.add(array[key]);
            }
          }
        } else {
          result.add(array);
        }
      }
    } else {
      console.log('类型错误');
    }
  }

  complierOriginData(JsonFile);

  result.forEach((item) => {
    for (const key in item) {
      if (Array.isArray(item[key]) || item[key] instanceof Object) {
        delete item[key];
      }
    }
  });

  const columns = Object.keys(Object.assign({}, ...result));

  columns.forEach((col) => {
    table.addColumn(new Column({ name: col }));
  });

  const rows = [];

  [...result].filter((k) => Object.keys(k).length > 0).forEach((row) => {
    let _temp = [];

    for (const key in row) {
      for (let i = 0; i < columns.length; i++) {
        if (key === columns[i]) {
          _temp[i] = row[key];
        }
      }
    }

    rows.push(_temp);
  });

  rows.forEach((row) => { table.addRow(new Row(row)) });
  sheet.addTable(table);

  const outputPath = path.resolve(__dirname, outputFilename);

  workbook.xlsx.writeFile(outputPath).then(function () {
    console.log('转化完成');
    process.exit(1);
  });
}
